package com.small.xx.ai.spring.vector.redis;

import com.alibaba.cloud.ai.autoconfigure.memory.RedisChatMemoryProperties;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.embedding.TokenCountBatchingStrategy;
import org.springframework.ai.vectorstore.redis.RedisVectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPooled;

/**
 * docker run --name langchain-redis -d -p 6380:6379 redis/redis-stack-server
 */
@Configuration
@ConditionalOnProperty(prefix = "spring.ai.vectorstore.redis", name = "enabled", havingValue = "true")
public class RedisVectorConfig {

    private static final Logger logger = LoggerFactory.getLogger(RedisVectorConfig.class);
    @Value("${spring.ai.vectorstore.redis.host}")
    private String host;
    @Value("${spring.ai.vectorstore.redis.port}")
    private int port;
    @Value("${spring.ai.vectorstore.redis.prefix:prefix_xx_}")
    private String prefix;
    @Value("${spring.ai.vectorstore.redis.index-name:index_xx_}")
    private String indexName;

    @Bean
    public JedisPooled jedisPooled() {
        logger.info("RedisVectorConfig Redis host: {}, port: {}", host, port);
        return new JedisPooled(host, port);
    }

    /**
     * embedding/embedding-model-dimensions.properties 支持的模型
     * @param jedisPooled
     * @param embeddingModel
     * @return
     */
    @Bean
    @Qualifier("redisVectorStoreCustom")
    public RedisVectorStore vectorStore(JedisPooled jedisPooled, EmbeddingModel embeddingModel) {
        logger.info("RedisVectorConfig create redis vector store");
        return RedisVectorStore.builder(jedisPooled, embeddingModel)
            .indexName(indexName)                // Optional: defaults to "spring-ai-index"
            .prefix(prefix)                  // Optional: defaults to "embedding:"
            .metadataFields(                         // Optional: define metadata fields for filtering
                RedisVectorStore.MetadataField.tag("name"), RedisVectorStore.MetadataField.numeric("year"))
            .initializeSchema(true)                   // Optional: defaults to false
            .batchingStrategy(new TokenCountBatchingStrategy()) // Optional: defaults to TokenCountBatchingStrategy
            .build();
    }

}
